(function () {

    var $view;
    var lastTabTwoClick = -37546; // 双击刷新
    var loginInfo = null;

    window.onShowIndex = function (e) {
        document.addEventListener("backbutton", app.onBackButton, false);

        document.removeEventListener("backbutton", app.onUpdateDefaultBackButton, false);
    };

    window.onHideIndex = function (e) {
        document.removeEventListener("backbutton", app.onBackButton, false);

        document.addEventListener("backbutton", app.onUpdateDefaultBackButton, false);
    };

    function onInit() {

        loginInfo = backService.localLoginInfo;
        utils.onTabBtn(); // 双击刷新
        utils.onShowPopupMenu();
        utils.onScrollEvent();
    }

    /**
     * 工具函数
     * @type {{onTabBtn: onTabBtn}}
     */
    window.utils = {
        onTabBtn: function () { // 底部选项卡
            $('.tab-bar').on("click", 'a.tab-item', function () {
                var index = $(this).index();

                var b = $(this).hasClass("active");

                if (b) {
                    var nNow = Number(new Date().getTime());
                    if (nNow - lastTabTwoClick < 2000) { // 双击

                        lastTabTwoClick = -37546;
                    } else {
                        lastTabTwoClick = nNow;
                    }
                    return false;
                } else {
                    if (index != 2) {
                        $(this).addClass("active").siblings().removeClass("active");
                    }
                }
                switch (index) {
                    case 0:
                        app.gotoPage("/");
                        break;
                    case 1:
                        app.gotoPage("/find/index.html");
                        break;
                    case 2:
                        app.gotoPage("/wirte/index.html");
                        break;
                    case 3:
                        app.gotoPage("/message/index.html");
                        break;
                    case 4:
                        app.gotoPage("/user/index.html");
                        break;
                }
            });
        },
        onShowPopupMenu: function () {// 显示/隐藏关注项目菜单
            var $drop = $view.find('.menu-backdrop');
            // 初始化设置首页关注的项目
            var settings = app.getSetting();
            var value = settings.follow_pjt;

            if (!value) {// 如果没有设置过，默认选择第一个
                $drop.find('.list li').eq(0).addClass('active');
                var $li = $drop.find('.list li').eq(0);
                $view.find('.follow').text($li.find("span").text());
                utils.onDisplayCurrItem("0");
            } else {// 选择对应的项目
                $drop.find(".list li[value=" + value + "]").addClass("active");
                $view.find('.follow').text($drop.find(".list li[value=" + value + "]").find("span").text());
                utils.onDisplayCurrItem(value);
            }


            $view.find('.follow').on('click', function () {
                $drop.fadeIn();

                // 隐藏函数
                function onHidePopDown() {
                    $drop.fadeOut();
                    document.removeEventListener("backbutton", onHidePopDown, false);
                }

                // 触控隐藏关注项目菜单
                $drop.on("click", function (e) {
                    if (e.target != this) {
                        return;
                    }
                    onHidePopDown();
                });

                // 设置关注项目
                var $li = $drop.find('.popup_menu_follow li.item');
                $li.on("click", function () {
                    var that = $(this);
                    var b = that.hasClass("active");
                    if (!b) {
                        that.addClass("active").siblings().removeClass("active");
                        $view.find('.follow').text(that.find('span').text());
                        var value = that.attr("value");
                        utils.onDisplayCurrItem(value);
                        var settings = app.getSetting();
                        settings.follow_pjt = value;
                        app.setSetting(settings);
                    }
                    onHidePopDown();
                });
                document.addEventListener("backbutton", onHidePopDown, false);
            });
        },
        onDisplayCurrItem: function (tab) {// 显示当前tab的内容
            var $content = $view.find('#scroll1 .mui-scroll');
            backService.onInitIndex({userId: loginInfo.id, typeId: tab}, function (json) {
                $content.empty();
                if (tab == 0) {// 显示全部

                } else if (tab == 1) {
                    if (json.data.length > 0) {
                        var datas = json.data;
                        var $spec = $("<div class='special'></div>");
                        $spec.appendTo($content);
                        for (var i = 0; i < datas.length; i++) {
                            var data = datas[i];
                            var name = data.name;
                            var title = data.title != null ? data.title : "暂无投稿文章";
                            var $item = $('<div class="item">' +
                                '               <img src="img/message/index/head.jpg" class="image_avatar" alt="">' +
                                '               <div class="spec_con">' +
                                '                   <p class="title">' + name + '</p>' +
                                '                   <p class="desc ellipsis">' + title + '</p>' +
                                '               </div>' +
                                '            </div>');
                            $item.appendTo($content.find('.special'));
                        }
                    }
                }
                utils.pullToRefresh();
            });
        },
        pullToRefresh: function () {
            mui('.mui-slider-group .mui-scroll').pullToRefresh({
                down: {
                    callback: function () {
                        var self = this;
                        setTimeout(function () {
                            self.endPullDownToRefresh();
                        }, 1000);
                    }
                },
                up: {
                    callback: function () {
                        var self = this;
                        setTimeout(function () {
                            self.endPullUpToRefresh();
                        }, 1000);
                    }
                }
            });
        },
        onScrollEvent: function () {

        }

    };

    /**
     * 验证用户是否登陆过
     */
    function onValidUserLogin() {
        // console.log(loginInfo);
        if (loginInfo && loginInfo.id) {
            var data = {
                acc: loginInfo.mobile,
                pass: loginInfo.password
            };
            backService.user.onLogin(data, function (json) {
                // var userInfo = json.data;
                if (json.data != null) {
                    if (backService.socket == null) {
                        onStartWebSocket();
                    }
                } else {
                    app.showToast("请先登录");
                    app.gotoPage("/user/login.html");
                }
            }, function (error) {
                app.showToast(error.msg);
            });
        } else {
            app.gotoPage("/user/login.html");
        }
    }

    /**
     * 启动websocket
     */
    function onStartWebSocket() {
        var path = backService.baseIp;

        if ('WebSocket' in window) {
            //创建socket对象
            // backService.socket = new WebSocket("ws://" + path + "/"+backService.context+"/ws");
            backService.socket = new ReconnectingWebSocket("ws://" + path + "/" + backService.context + "/ws");
        } else if ('MozWebSocket' in window) {
            backService.socket = new MozWebSocket("ws://" + path + "/" + backService.context + "/ws");
        } else {
            backService.socket = new SockJS("http://" + path + "/" + backService.context + "/ws/sockjs");
        }
    }

    /*初始化*/
    window.onViewInit_index = function (view) {
        $view = view.element;
        mui.init();
        var deceleration = mui.os.ios ? 0.003 : 0.0009;
        mui('.mui-scroll-wrapper').scroll({
            bounce: false,
            indicators: true, //是否显示滚动条
            deceleration: deceleration
        });
        onInit();
    };

    window.onViewShow_index = function (view) {
        $view = view.element;

        onValidUserLogin();

        app.onBackTabItemActive($view, 0);
    };

})();